<script lang="ts" setup>
import { ref, reactive, onMounted, computed, h } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { 
  Card, Table, Button, Input, Space, Form, Tabs, Tag, Tooltip, 
  message, Modal, Descriptions, Divider
} from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';
import { 
  getSettlementDetailApi,
  batchPaySettlementApi,
  triggerSettlementTaxApi,
  type SettlementApi 
} from '#/api/core/settlement';
import {
  getSubSettlementListApi,
  verifySubSettlementApi,
  submitSubSettlementApi,
  distributeSubSettlementApi,
  cancelSubSettlementApi,
  deleteSubSettlementApi,
  updateSubSettlementApi,
  type SubSettlementApi,
} from '#/api/core/sub-settlement';

interface PaginationData {
  current: number;
  pageSize: number;
  total: number;
  showSizeChanger: boolean;
  showQuickJumper: boolean;
  pageSizeOptions: string[];
  showTotal: (total: number, range: [number, number]) => string;
}

// 路由
const route = useRoute();
const router = useRouter();

// 响应式数据
const loading = ref(false);
const subSettlementLoading = ref(false);
const deletingSubSettlementId = ref<string | null>(null);
const settlementDetail = ref<SettlementApi.SettlementRecord | null>(null);
const subSettlements = ref<SubSettlementApi.SubSettlementRecord[]>([]);
const activeTab = ref('all');
const batchPayLoading = ref(false);

// 搜索表单
const searchForm = reactive({
  name: '',
  phone: '',
  idCard: ''
});

// 分页数据
const pagination = reactive<PaginationData>({
  current: 1,
  pageSize: 15,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  pageSizeOptions: ['10', '15', '20', '50'],
  showTotal: (total: number, range: [number, number]) => 
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
});

// Tabs配置
const statusTabs = [
  { key: 'all', label: '全部' },
  { key: '验证中', label: '验证中' },
  { key: '待算税', label: '待算税' },
  { key: '待提交', label: '待提交' },
  { key: '待发放', label: '待发放' },
  { key: '发放中', label: '发放中' },
  { key: '已完成', label: '已完成' },
  { key: '已取消', label: '已取消' },
  { key: '发放失败', label: '发放失败' },
  { key: '验证失败', label: '验证失败' },
  { key: '已退票', label: '已退票' }
];

// 计算属性 - 结算单统计
const settlementStats = computed(() => {
  if (!subSettlements.value.length) {
    return {
      totalCommission: 0,
      totalServiceFee: 0,
      totalTax: 0,
      totalRequiredBalance: 0,
      statusCounts: {} as Record<string, number>,
    };
  }

  const stats = {
    totalCommission: 0,
    totalServiceFee: 0,
    totalTax: 0,
    totalRequiredBalance: 0,
    statusCounts: {} as Record<string, number>
  };

  subSettlements.value.forEach(item => {
    stats.totalCommission += item.commission;
    stats.totalServiceFee += item.service_fee;
    stats.totalTax += item.tax ?? 0;
    const requiredBalance = Number((item as any).required_balance ?? (item as any).requiredBalance ?? 0);
    stats.totalRequiredBalance += requiredBalance;
    stats.statusCounts[item.status] = (stats.statusCounts[item.status] || 0) + 1;
  });
  
  return stats;
});

// 表格列定义
const columns: TableColumnsType<SubSettlementApi.SubSettlementRecord> = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 100,
    ellipsis: true,
  },
  {
    title: '银行卡号',
    dataIndex: 'bank_account',
    key: 'bank_account',
    width: 140,
    ellipsis: true,
    customRender: ({ text }) => {
      if (!text) return '-';
      // 脱敏显示银行卡号
      const masked = text.replace(/(\d{4})\d*(\d{4})/, '$1****$2');
      return h(Tooltip, { title: `完整卡号: ${text}` }, () => masked);
    },
  },
  {
    title: '状态',
    dataIndex: 'status_display',
    key: 'status',
    width: 100,
    customRender: ({ record }) => {
      const statusColorMap: Record<string, string> = {
        '验证中': 'processing',
        '待算税': 'processing',
        '待提交': 'default',
        '待发放': 'warning',
        '发放中': 'processing',
        '已完成': 'success',
        '已取消': 'default',
        '发放失败': 'error',
        '验证失败': 'error',
        '已退票': 'warning'
      };
      
      const tagColor = statusColorMap[record.status] ?? 'default';
      return h(Tag, { color: tagColor }, () => record.status_display);
    },
  },
  {
    title: '状态说明',
    dataIndex: 'status_desc',
    key: 'status_desc',
    width: 120,
    ellipsis: true,
    customRender: ({ text }) => {
      return text ? h(Tooltip, { title: text }, () => text) : '-';
    },
  },
  {
    title: '税前佣金(元)',
    dataIndex: 'pre_settlement_amount',
    key: 'pre_settlement_amount',
    width: 140,
    align: 'right',
    customRender: ({ text }) => `¥${Number(text ?? 0).toLocaleString()}`,
  },
  {
    title: '个税(元)',
    dataIndex: 'tax',
    key: 'tax',
    width: 120,
    align: 'right',
    customRender: ({ text }) => `¥${Number(text ?? 0).toLocaleString()}`,
  },
  {
    title: '佣金(元)',
    dataIndex: 'commission',
    key: 'commission',
    width: 120,
    align: 'right',
    customRender: ({ text }) => `¥${Number(text).toLocaleString()}`,
  },
  {
    title: '服务费(元)',
    dataIndex: 'service_fee',
    key: 'service_fee',
    width: 120,
    align: 'right',
    customRender: ({ text }) => `¥${Number(text).toLocaleString()}`,
  },
  {
    title: '所需余额(元)',
    dataIndex: 'required_balance',
    key: 'required_balance',
    width: 140,
    align: 'right',
    customRender: ({ text }) => `¥${Number(text ?? 0).toLocaleString()}`,
  },
  {
    title: '发放时间',
    dataIndex: 'release_time',
    key: 'release_time',
    width: 160,
    customRender: ({ text }) => {
      return text ? new Date(text).toLocaleString('zh-CN') : '-';
    },
  },
  {
    title: '电子回单',
    key: 'receipt',
    width: 100,
    customRender: ({ record }) => {
      if (!record.electronic_receipt) return '-';
      
      return h(Space, { size: 'small' }, [
        h(Button, { 
          type: 'link', 
          size: 'small',
          onClick: () => handlePreviewReceipt(record)
        }, '预览'),
        h(Button, { 
          type: 'link', 
          size: 'small',
          onClick: () => handleDownloadReceipt(record)
        }, '下载')
      ]);
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 260,
    fixed: 'right',
    customRender: ({ record }) => {
      const actions: ReturnType<typeof h>[] = [];

      if (record.status === '验证失败') {
        actions.push(
          h(
            Button,
            {
              type: 'link',
              size: 'small',
              onClick: () => openEditModal(record),
            },
            () => '编辑',
          ),
        );
      }

      if (record.canOfflineAuth) {
        actions.push(
          h(
            Button,
            {
              type: 'link',
              size: 'small',
              onClick: () => handleOfflineAuth(record.id),
            },
            () => '线下认证',
          ),
        );
      }

      if (record.canCancel) {
        actions.push(
          h(
            Button,
            {
              type: 'link',
              size: 'small',
              onClick: () => handleCancel(record.id),
            },
            () => '取消',
          ),
        );
      }

      const lockedStatuses = ['待发放', '发放中', '已完成', '已退票'];
      if (!lockedStatuses.includes(record.status)) {
        actions.push(
          h(
            Button,
            {
              type: 'link',
              size: 'small',
              danger: true,
              onClick: () => handleDeleteSubSettlement(record),
            },
            () => '删除',
          ),
        );
      }

      return h(Space, { size: 'small' }, () => actions);
    },
  },
];

// 获取结算单详情
const fetchSettlementDetail = async () => {
  try {
    loading.value = true;
    const settlementId = route.params.id as string;
    
    const response = await getSettlementDetailApi(settlementId);
    // 适配封装层返回风格（可能直接是记录，也可能包裹在 data 内）
    settlementDetail.value = (response as any)?.data ?? response ?? null;
  } catch (error) {
    console.error('获取结算单详情失败:', error);
    message.error('网络请求失败');
  } finally {
    loading.value = false;
  }
};

// 获取子结算单列表
const fetchSubSettlements = async () => {
  try {
    subSettlementLoading.value = true;
    const settlementId = route.params.id as string;
    
    const params = {
      settlement_id: settlementId,
      status: activeTab.value === 'all' ? undefined : activeTab.value,
      name: searchForm.name.trim() || undefined,
      phone: searchForm.phone.trim() || undefined,
      id_card: searchForm.idCard.trim() || undefined,
      page: pagination.current,
      per_page: pagination.pageSize,
    };
    
    console.log('📤 发送子结算单查询请求:', params);
    
    const response = await getSubSettlementListApi(params);
    console.log('📥 子结算单API响应:', response);
    
    subSettlements.value = response.data ?? [];
    pagination.total = response.total ?? 0;
    pagination.current = response.current_page ?? 1;
    
    console.log('✅ 子结算单数据更新成功:', {
      count: subSettlements.value.length,
      total: pagination.total,
      current: pagination.current
    });
  } catch (error) {
    console.error('❌ 获取子结算单列表失败:', error);
    message.error('网络请求失败');
    subSettlements.value = [];
    pagination.total = 0;
  } finally {
    subSettlementLoading.value = false;
  }
};

// 搜索操作
const handleSearch = () => {
  pagination.current = 1;
  fetchSubSettlements();
};

// 重置搜索条件
const handleReset = () => {
  searchForm.name = '';
  searchForm.phone = '';
  searchForm.idCard = '';
  pagination.current = 1;
  fetchSubSettlements();
};

const showBatchPayButton = computed(() => activeTab.value === '待提交');
const isBatchPayDisabled = computed(
  () => batchPayLoading.value || !settlementDetail.value || subSettlements.value.length === 0,
);

const handleBatchPay = () => {
  if (!settlementDetail.value) return;

  const currentSettlement = settlementDetail.value;

  Modal.confirm({
    title: '确认批量发放',
    content: '将对当前结算单的待提交子结算单发起批量发放，是否继续？',
    okText: '确定',
    cancelText: '取消',
    async onOk() {
      try {
        batchPayLoading.value = true;
        await batchPaySettlementApi(currentSettlement.settlement_number);
        message.success('批量发放任务已提交');
        fetchSubSettlements();
      } catch (error) {
        console.error('批量发放失败:', error);
        message.error('批量发放任务提交失败');
      } finally {
        batchPayLoading.value = false;
      }
    },
  });
};

// Tab切换处理
const handleTabChange = (key: string) => {
  activeTab.value = key;
  pagination.current = 1;
  fetchSubSettlements();
};

// 分页变化处理
const handleTableChange = (paginationParams: any) => {
  pagination.current = paginationParams.current;
  pagination.pageSize = paginationParams.pageSize;
  fetchSubSettlements();
};

// 操作处理函数
const editModalVisible = ref(false);
const editForm = reactive({
  id: '',
  name: '',
  phone: '',
  bank_account: '',
});
const editSubmitting = ref(false);

const openEditModal = (record: SubSettlementApi.SubSettlementRecord) => {
  editForm.id = record.id;
  editForm.name = record.name;
  editForm.phone = record.phone;
  editForm.bank_account = record.bankAccount ?? record.bank_account ?? '';
  editModalVisible.value = true;
};

const handleOfflineAuth = (id: string) => {
  Modal.confirm({
    title: '确认线下认证',
    content: '确认该笔款项已成功发放？',
    onOk: async () => {
      try {
        const response = await distributeSubSettlementApi(id, {
          action: 'complete',
          remarks: '线下认证完成'
        });
        
        message.success('线下认证成功');
        fetchSubSettlements();
      } catch (error) {
        message.error('操作失败');
      }
    }
  });
};

const handleCancel = (id: string) => {
  Modal.confirm({
    title: '确认取消',
    content: '确认取消这个子结算单？',
    onOk: async () => {
      try {
        const response = await cancelSubSettlementApi(id, {
          remarks: '用户取消'
        });
        
        message.success('取消成功');
        fetchSubSettlements();
      } catch (error) {
        message.error('取消失败');
      }
    }
  });
};

const handleDeleteSubSettlement = (record: SubSettlementApi.SubSettlementRecord) => {
  const lockedStatuses = ['待发放', '发放中', '已完成', '已退票'];
  if (lockedStatuses.includes(record.status)) {
    message.warning('当前状态的子结算单无法删除');
    return;
  }

  Modal.confirm({
    title: '确认删除该子结算单？',
    content: '删除后将无法恢复，请确认该子结算单尚未进入发放流程。',
    okText: '删除',
    okButtonProps: { danger: true },
    cancelText: '取消',
    async onOk() {
      deletingSubSettlementId.value = record.id;
      try {
        await deleteSubSettlementApi(record.id);
        message.success('子结算单删除成功');
        fetchSubSettlements();
      } catch (error) {
        console.error('删除子结算单失败:', error);
        const errorMessage =
          error?.response?.data?.message || error?.message || '删除子结算单失败，请稍后重试';
        message.error(errorMessage);
      } finally {
        deletingSubSettlementId.value = null;
      }
    },
  });
};

const handleSubmitEdit = async () => {
  if (!editForm.id) return;
  if (!editForm.bank_account || editForm.bank_account.trim().length < 8) {
    message.warning('请填写有效的银行卡号');
    return;
  }
  editSubmitting.value = true;
  try {
    await updateSubSettlementApi(editForm.id, {
      freelancer_bank_account: editForm.bank_account.trim(),
    });
    message.success('银行卡号已更新');
    editModalVisible.value = false;
    fetchSubSettlements();
  } catch (error) {
    console.error('更新银行卡号失败:', error);
    const errorMessage =
      error?.response?.data?.message || error?.message || '更新银行卡号失败，请稍后重试';
    message.error(errorMessage);
  } finally {
    editSubmitting.value = false;
  }
};

const isPendingTaxTab = computed(() => activeTab.value === '待算税');
const triggerTaxLoading = ref(false);

const handleTriggerTax = async () => {
  if (!settlementDetail.value) {
    message.warning('未获取到结算单详情');
    return;
  }
  Modal.confirm({
    title: '确认发起算税',
    content: '将向后台发起算税任务，请确认当前结算单信息无误。',
    okText: '发起算税',
    cancelText: '取消',
    async onOk() {
      try {
        triggerTaxLoading.value = true;
        await triggerSettlementTaxApi(settlementDetail.value.id);
        message.success('算税任务已触发');
        fetchSubSettlements();
        fetchSettlementDetail();
      } catch (error) {
        console.error('触发算税失败:', error);
        message.error('触发算税失败，请稍后重试');
      } finally {
        triggerTaxLoading.value = false;
      }
    },
  });
};

const handlePreviewReceipt = (record: SubSettlementApi.SubSettlementRecord) => {
  console.log('预览电子回单:', record.electronicReceipt);
  message.info('预览功能开发中...');
};

const handleDownloadReceipt = (record: SubSettlementApi.SubSettlementRecord) => {
  console.log('下载电子回单:', record.electronicReceipt);
  message.info('下载功能开发中...');
};

// 返回上一页
const handleBack = () => {
  router.push('/business-settlement');
};

// 组件挂载时加载数据
onMounted(() => {
  fetchSettlementDetail();
  fetchSubSettlements();
});
</script>

<template>
  <div class="p-5">
    <Card>
      <!-- 返回按钮 -->
      <div class="mb-4">
        <Button @click="handleBack">← 返回结算列表</Button>
      </div>
      
      <!-- 结算单详情卡片 -->
      <Card 
        title="结算单详情" 
        :loading="loading"
        class="mb-6"
      >
        <Descriptions 
          v-if="settlementDetail"
          :column="3"
          size="middle"
        >
          <Descriptions.Item label="结算单ID">
            <Tooltip :title="`完整ID: ${settlementDetail.id}`">
              {{ settlementDetail.settlement_number || '未生成编号' }}
            </Tooltip>
          </Descriptions.Item>
          <Descriptions.Item label="结算单名称">
            {{ settlementDetail.settlement_name || '未命名结算单' }}
          </Descriptions.Item>
          <Descriptions.Item label="创建时间">
            {{ settlementDetail.created_at ? new Date(settlementDetail.created_at).toLocaleString('zh-CN') : '-' }}
          </Descriptions.Item>
          <Descriptions.Item label="落地公司">
            {{ settlementDetail.landing_company || '-' }}
          </Descriptions.Item>
          <Descriptions.Item label="服务类型">
            {{ settlementDetail.task_name || '通用服务' }}
          </Descriptions.Item>
          <Descriptions.Item label="状态">
            <Tag :color="settlementDetail.status === 'completed' ? 'success' : 'processing'">
              {{ settlementDetail.status_display }}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="总税前佣金">
            <span class="text-lg font-semibold text-blue-600">
              ¥{{ Number(settlementDetail.total_amount).toLocaleString() }}
            </span>
          </Descriptions.Item>
          <Descriptions.Item label="总个税">
            <span class="text-lg font-semibold text-red-500">
              ¥{{ Number(settlementStats.totalTax || 0).toLocaleString() }}
            </span>
          </Descriptions.Item>
          <Descriptions.Item label="总佣金">
            <span class="text-lg font-semibold text-green-600">
              ¥{{ Number(settlementStats.totalCommission || 0).toLocaleString() }}
            </span>
          </Descriptions.Item>
          <Descriptions.Item label="总服务费">
            <span class="text-lg font-semibold text-orange-600">
              ¥{{ Number(settlementStats.totalServiceFee || 0).toLocaleString() }}
            </span>
          </Descriptions.Item>
          <Descriptions.Item label="总所需余额">
            <span class="text-lg font-semibold text-purple-600">
              ¥{{ Number(settlementStats.totalRequiredBalance || 0).toLocaleString() }}
            </span>
          </Descriptions.Item>
        </Descriptions>
      </Card>

      <!-- 发放列表区域 -->
      <Card title="发放列表">
        <!-- Tab筛选 -->
        <Tabs v-model:activeKey="activeTab" @change="handleTabChange" class="mb-4">
          <Tabs.TabPane 
            v-for="tab in statusTabs" 
            :key="tab.key" 
            :tab="tab.label"
          />
        </Tabs>

        <!-- 搜索区域 -->
        <div class="mb-4">
          <Form layout="inline" :model="searchForm">
            <Form.Item label="姓名" name="name">
              <Input
                v-model:value="searchForm.name"
                placeholder="请输入姓名"
                style="width: 160px"
                allowClear
                @pressEnter="handleSearch"
              />
            </Form.Item>
            
            <Form.Item label="手机号" name="phone">
              <Input
                v-model:value="searchForm.phone"
                placeholder="请输入手机号"
                style="width: 160px"
                allowClear
                @pressEnter="handleSearch"
              />
            </Form.Item>
            
            <Form.Item label="身份证号" name="idCard">
              <Input
                v-model:value="searchForm.idCard"
                placeholder="请输入身份证号"
                style="width: 160px"
                allowClear
                @pressEnter="handleSearch"
              />
            </Form.Item>
            
            <Form.Item>
              <Space>
                <Button 
                  type="primary" 
                  @click="handleSearch"
                  :loading="subSettlementLoading"
                >
                  查询
                </Button>
                <Button @click="handleReset">
                  重置
                </Button>
                <Button
                  v-if="isPendingTaxTab"
                  type="primary"
                  :loading="triggerTaxLoading"
                  @click="handleTriggerTax"
                >
                  算税
                </Button>
                <Button
                  v-if="showBatchPayButton"
                  type="primary"
                  ghost
                  :loading="batchPayLoading"
                  :disabled="isBatchPayDisabled"
                  @click="handleBatchPay"
                >
                  批量发放
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </div>
        
        <!-- 数据表格 -->
        <Table
          :columns="columns"
          :data-source="subSettlements"
          :loading="subSettlementLoading"
          :pagination="pagination"
          row-key="id"
          :scroll="{ x: 1400 }"
          @change="handleTableChange"
        />
      </Card>
    </Card>

    <Modal
      v-model:open="editModalVisible"
      title="编辑银行卡号"
      :confirm-loading="editSubmitting"
      ok-text="保存"
      cancel-text="取消"
      destroy-on-close
      @ok="handleSubmitEdit"
      @cancel="() => (editModalVisible = false)"
    >
      <Form layout="vertical">
        <Form.Item label="姓名">
          <Input :value="editForm.name" disabled />
        </Form.Item>
        <Form.Item label="手机号">
          <Input :value="editForm.phone" disabled />
        </Form.Item>
        <Form.Item label="银行卡号" required>
          <Input
            v-model:value="editForm.bank_account"
            maxlength="32"
            placeholder="请输入银行卡号"
          />
        </Form.Item>
      </Form>
    </Modal>
  </div>
</template>

<style scoped>
.ant-table-tbody > tr > td {
  padding: 12px 8px;
}

.ant-form-item {
  margin-bottom: 16px;
}

.ant-descriptions-item-label {
  font-weight: 500;
}

.text-lg {
  font-size: 1.125rem;
}

.font-semibold {
  font-weight: 600;
}

.text-blue-600 {
  color: #2563eb;
}

.text-green-600 {
  color: #16a34a;
}

.text-orange-600 {
  color: #ea580c;
}

.text-red-500 {
  color: #ef4444;
}

.text-purple-600 {
  color: #7c3aed;
}
</style>
